import { store, useUserStore } from "@/store";
import { getGlobalConfig, refreshGlobalConfig } from "@/api/configuration";

export const useGlobalConfigStore = defineStore("config", () => {
  const globalConfiguration = ref<any>({});
  // 查询全局配置
  function getGlobalConfiguration() {
    return new Promise<any>((resolve, reject) => {
      getGlobalConfig({})
        .then(({ data }: { data: any }) => {
          Object.assign(globalConfiguration.value, { ...data });
          console.log(globalConfiguration.value);
          resolve(data);
        })
        .catch((error: any) => {
          console.log("获取全局配置接口请求异常," + error);
          ElMessage({
            showClose: true,
            type: "error",
            message: error,
          });
          reject(error);
        });
    });
  }

  function refreshGlobalConfiguration(prefix: string) {
    return new Promise<any>((resolve, reject) => {
      refreshGlobalConfig(prefix)
        .then(({ data }: { data: any }) => {
          console.log(data);
          resolve(data);
        })
        .catch((error: any) => {
          console.log("更新全局配置接口请求异常," + error);
          reject(error);
        });
    });
  }

  function isAdministratorRole() {
    const userinfo: any = (useUserStore() as any).user;
    return (
      globalConfiguration.value["administrator"] &&
      JSON.parse(globalConfiguration.value["administrator"]).indexOf(
        userinfo.username
      ) !== -1
    );
  }

  return {
    globalConfiguration,
    getGlobalConfiguration,
    refreshGlobalConfiguration,
    isAdministratorRole,
  };
});

// 非setup
export function useGlobalConfigHook() {
  return useGlobalConfigStore(store);
}
